package edu.kit.csl.cratyli.control;

import java.io.IOException;

import edu.kit.csl.cratyli.datatypes.BadParameterValueException;
import edu.kit.csl.cratyli.datatypes.Dictionary;
import edu.kit.csl.cratyli.datatypes.TextCorpus;
import edu.kit.csl.cratyli.ui.Configuration;
import edu.kit.csl.cratyli.ui.Logger;

/**
 * This module controls the order in which cratylus runs are combined together.
 */
abstract public class CombinationOrderStrategy {
	/**
	 * primaryCratylus run parameter. Path to the primary cratylus run.
	 */
	protected String primPath;
	/**
	 * Split secondary cratylus runs.
	 */
	protected String[] secPaths;
	
	protected CombinationStrategy combiner;
	protected ReductionStrategy reducer;
	protected double minWeight;
	
	private int dumpFreq;
	private String outputPrefix;
	
	/**
	 * Sole constructor. Fetches the protected class variables primPath and
	 * secPaths and initializes the combination and reduction strategy.
	 */
	public CombinationOrderStrategy() throws BadParameterValueException {
		Configuration conf = Configuration.getSingleton();
		combiner = new M2MCombinationStrategy();
		reducer = new OccurrenceReductionStrategy();
		primPath = conf.getString("primaryCratylusPath").trim();
		secPaths = conf.getString("secondaryCratylusPaths").trim().split(" ");
		Logger.getSingleton().notice("Registrated " + secPaths.length
				+ " secondary cratylus runs.");
		dumpFreq = conf.getInteger("dumpFrequency");
		minWeight = conf.getFloat("minimumWordWeight");
		outputPrefix = conf.getString("outputPrefix") + ".";
	}
	
	/**
	 * Combine the primary cratylus run with the secondary runs. This method
	 * is implemented by subclasses.
	 */
	abstract public void startCombining();

	/**
	 * Writes a dictionary and a corpus to the file system, if n % dump
	 * frequency is zero.
	 * 
	 * @param tag String identifier which is added to the output prefix
	 * @param n only dump if n % dumpFrequency is 0
	 * @param dict dictionary to dump
	 * @param corpus text corpus to dump
	 */
	protected void writeToFileSystem(String tag, int n,
			Dictionary dict, TextCorpus corpus) {
		if (n % dumpFreq != 0) {
			return;
		}
		Logger.getSingleton().notice("Dump to " + outputPrefix + tag);
		try {
			dict.writeToFileSystem(outputPrefix + tag + ".dict");
			corpus.writeToFileSystem(outputPrefix + tag);
		} catch (IOException e) {
			Logger.getSingleton().error("Could not dump to " + outputPrefix
				+ tag + ": " + e.getMessage());
		}
	}
}
